home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / var / lib / python-support / python2.6 / dbus / connection.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  20.3 KB  |  541 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __all__ = ('Connection', 'SignalMatch')
  5. __docformat__ = 'reStructuredText'
  6. import logging
  7.  
  8. try:
  9.     import thread
  10. except ImportError:
  11.     import dummy_thread as thread
  12.  
  13. import weakref
  14. from _dbus_bindings import Connection as _Connection, LOCAL_PATH, LOCAL_IFACE, validate_interface_name, validate_member_name, validate_bus_name, validate_object_path, validate_error_name, UTF8String
  15. from dbus.exceptions import DBusException
  16. from dbus.lowlevel import ErrorMessage, MethodCallMessage, SignalMessage, MethodReturnMessage, HANDLER_RESULT_NOT_YET_HANDLED
  17. from dbus.proxies import ProxyObject
  18. _logger = logging.getLogger('dbus.connection')
  19.  
  20. def _noop(*args, **kwargs):
  21.     pass
  22.  
  23.  
  24. class SignalMatch(object):
  25.     __slots__ = ('_sender_name_owner', '_member', '_interface', '_sender', '_path', '_handler', '_args_match', '_rule', '_utf8_strings', '_byte_arrays', '_conn_weakref', '_destination_keyword', '_interface_keyword', '_message_keyword', '_member_keyword', '_sender_keyword', '_path_keyword', '_int_args_match')
  26.     
  27.     def __init__(self, conn, sender, object_path, dbus_interface, member, handler, utf8_strings = False, byte_arrays = False, sender_keyword = None, path_keyword = None, interface_keyword = None, member_keyword = None, message_keyword = None, destination_keyword = None, **kwargs):
  28.         if member is not None:
  29.             validate_member_name(member)
  30.         
  31.         if dbus_interface is not None:
  32.             validate_interface_name(dbus_interface)
  33.         
  34.         if sender is not None:
  35.             validate_bus_name(sender)
  36.         
  37.         if object_path is not None:
  38.             validate_object_path(object_path)
  39.         
  40.         self._rule = None
  41.         self._conn_weakref = weakref.ref(conn)
  42.         self._sender = sender
  43.         self._interface = dbus_interface
  44.         self._member = member
  45.         self._path = object_path
  46.         self._handler = handler
  47.         self._sender_name_owner = sender
  48.         self._utf8_strings = utf8_strings
  49.         self._byte_arrays = byte_arrays
  50.         self._sender_keyword = sender_keyword
  51.         self._path_keyword = path_keyword
  52.         self._member_keyword = member_keyword
  53.         self._interface_keyword = interface_keyword
  54.         self._message_keyword = message_keyword
  55.         self._destination_keyword = destination_keyword
  56.         self._args_match = kwargs
  57.         if not kwargs:
  58.             self._int_args_match = None
  59.         else:
  60.             self._int_args_match = { }
  61.             for kwarg in kwargs:
  62.                 if not kwarg.startswith('arg'):
  63.                     raise TypeError('SignalMatch: unknown keyword argument %s' % kwarg)
  64.                 kwarg.startswith('arg')
  65.                 
  66.                 try:
  67.                     index = int(kwarg[3:])
  68.                 except ValueError:
  69.                     raise TypeError('SignalMatch: unknown keyword argument %s' % kwarg)
  70.  
  71.                 if index < 0 or index > 63:
  72.                     raise TypeError('SignalMatch: arg match index must be in range(64), not %d' % index)
  73.                 index > 63
  74.                 self._int_args_match[index] = kwargs[kwarg]
  75.             
  76.  
  77.     
  78.     def __hash__(self):
  79.         '''SignalMatch objects are compared by identity.'''
  80.         return hash(id(self))
  81.  
  82.     
  83.     def __eq__(self, other):
  84.         '''SignalMatch objects are compared by identity.'''
  85.         return self is other
  86.  
  87.     
  88.     def __ne__(self, other):
  89.         '''SignalMatch objects are compared by identity.'''
  90.         return self is not other
  91.  
  92.     sender = property((lambda self: self._sender))
  93.     
  94.     def __str__(self):
  95.         if self._rule is None:
  96.             rule = [
  97.                 "type='signal'"]
  98.             if self._sender is not None:
  99.                 rule.append("sender='%s'" % self._sender)
  100.             
  101.             if self._path is not None:
  102.                 rule.append("path='%s'" % self._path)
  103.             
  104.             if self._interface is not None:
  105.                 rule.append("interface='%s'" % self._interface)
  106.             
  107.             if self._member is not None:
  108.                 rule.append("member='%s'" % self._member)
  109.             
  110.             if self._int_args_match is not None:
  111.                 for index, value in self._int_args_match.iteritems():
  112.                     rule.append("arg%d='%s'" % (index, value))
  113.                 
  114.             
  115.             self._rule = ','.join(rule)
  116.         
  117.         return self._rule
  118.  
  119.     
  120.     def __repr__(self):
  121.         return '<%s at %x "%s" on conn %r>' % (self.__class__, id(self), self._rule, self._conn_weakref())
  122.  
  123.     
  124.     def set_sender_name_owner(self, new_name):
  125.         self._sender_name_owner = new_name
  126.  
  127.     
  128.     def matches_removal_spec(self, sender, object_path, dbus_interface, member, handler, **kwargs):
  129.         if handler not in (None, self._handler):
  130.             return False
  131.         if sender != self._sender:
  132.             return False
  133.         if object_path != self._path:
  134.             return False
  135.         if dbus_interface != self._interface:
  136.             return False
  137.         if member != self._member:
  138.             return False
  139.         if kwargs != self._args_match:
  140.             return False
  141.         return True
  142.  
  143.     
  144.     def maybe_handle_message(self, message):
  145.         args = None
  146.         if self._sender_name_owner not in (None, message.get_sender()):
  147.             return False
  148.         if self._member not in (None, message.get_member()):
  149.             return False
  150.         if self._interface not in (None, message.get_interface()):
  151.             return False
  152.         if self._path not in (None, message.get_path()):
  153.             return False
  154.         
  155.         try:
  156.             kwargs = { }
  157.             if self._destination_keyword is not None:
  158.                 kwargs[self._destination_keyword] = message.get_destination()
  159.             
  160.             if self._path_keyword is not None:
  161.                 kwargs[self._path_keyword] = message.get_path()
  162.             
  163.             if self._member_keyword is not None:
  164.                 kwargs[self._member_keyword] = message.get_member()
  165.             
  166.             if self._interface_keyword is not None:
  167.                 kwargs[self._interface_keyword] = message.get_interface()
  168.             
  169.             if self._message_keyword is not None:
  170.                 kwargs[self._message_keyword] = message
  171.             
  172.             self._handler(*args, **kwargs)
  173.         except:
  174.             self._path not in (None, message.get_path())
  175.             self._interface not in (None, message.get_interface())
  176.             self._member not in (None, message.get_member())
  177.             logging.basicConfig()
  178.             _logger.error('Exception in handler for D-Bus signal:', exc_info = 1)
  179.  
  180.         return True
  181.  
  182.     
  183.     def remove(self):
  184.         conn = self._conn_weakref()
  185.         if conn is not None:
  186.             conn.remove_signal_receiver(self, self._member, self._interface, self._sender, self._path, **self._args_match)
  187.         
  188.  
  189.  
  190.  
  191. class Connection(_Connection):
  192.     '''A connection to another application. In this base class there is
  193.     assumed to be no bus daemon.
  194.  
  195.     :Since: 0.81.0
  196.     '''
  197.     ProxyObjectClass = ProxyObject
  198.     
  199.     def __init__(self, *args, **kwargs):
  200.         super(Connection, self).__init__(*args, **kwargs)
  201.         if not hasattr(self, '_dbus_Connection_initialized'):
  202.             self._dbus_Connection_initialized = 1
  203.             self._Connection__call_on_disconnection = []
  204.             self._signal_recipients_by_object_path = { }
  205.             self._signals_lock = thread.allocate_lock()
  206.             self.add_message_filter(self.__class__._signal_func)
  207.         
  208.  
  209.     
  210.     def activate_name_owner(self, bus_name):
  211.         '''Return the unique name for the given bus name, activating it
  212.         if necessary and possible.
  213.  
  214.         If the name is already unique or this connection is not to a
  215.         bus daemon, just return it.
  216.  
  217.         :Returns: a bus name. If the given `bus_name` exists, the returned
  218.             name identifies its current owner; otherwise the returned name
  219.             does not exist.
  220.         :Raises DBusException: if the implementation has failed
  221.             to activate the given bus name.
  222.         :Since: 0.81.0
  223.         '''
  224.         return bus_name
  225.  
  226.     
  227.     def get_object(self, bus_name = None, object_path = None, introspect = True, **kwargs):
  228.         '''Return a local proxy for the given remote object.
  229.  
  230.         Method calls on the proxy are translated into method calls on the
  231.         remote object.
  232.  
  233.         :Parameters:
  234.             `bus_name` : str
  235.                 A bus name (either the unique name or a well-known name)
  236.                 of the application owning the object. The keyword argument
  237.                 named_service is a deprecated alias for this.
  238.             `object_path` : str
  239.                 The object path of the desired object
  240.             `introspect` : bool
  241.                 If true (default), attempt to introspect the remote
  242.                 object to find out supported methods and their signatures
  243.  
  244.         :Returns: a `dbus.proxies.ProxyObject`
  245.         '''
  246.         named_service = kwargs.pop('named_service', None)
  247.         if named_service is not None:
  248.             if bus_name is not None:
  249.                 raise TypeError('bus_name and named_service cannot both be specified')
  250.             bus_name is not None
  251.             warn = warn
  252.             import warnings
  253.             warn('Passing the named_service parameter to get_object by name is deprecated: please use positional parameters', DeprecationWarning, stacklevel = 2)
  254.             bus_name = named_service
  255.         
  256.         if kwargs:
  257.             raise TypeError('get_object does not take these keyword arguments: %s' % ', '.join(kwargs.iterkeys()))
  258.         kwargs
  259.         return self.ProxyObjectClass(self, bus_name, object_path, introspect = introspect)
  260.  
  261.     
  262.     def add_signal_receiver(self, handler_function, signal_name = None, dbus_interface = None, bus_name = None, path = None, **keywords):
  263.         """Arrange for the given function to be called when a signal matching
  264.         the parameters is received.
  265.  
  266.         :Parameters:
  267.             `handler_function` : callable
  268.                 The function to be called. Its positional arguments will
  269.                 be the arguments of the signal. By default it will receive
  270.                 no keyword arguments, but see the description of
  271.                 the optional keyword arguments below.
  272.             `signal_name` : str
  273.                 The signal name; None (the default) matches all names
  274.             `dbus_interface` : str
  275.                 The D-Bus interface name with which to qualify the signal;
  276.                 None (the default) matches all interface names
  277.             `bus_name` : str
  278.                 A bus name for the sender, which will be resolved to a
  279.                 unique name if it is not already; None (the default) matches
  280.                 any sender.
  281.             `path` : str
  282.                 The object path of the object which must have emitted the
  283.                 signal; None (the default) matches any object path
  284.         :Keywords:
  285.             `utf8_strings` : bool
  286.                 If True, the handler function will receive any string
  287.                 arguments as dbus.UTF8String objects (a subclass of str
  288.                 guaranteed to be UTF-8). If False (default) it will receive
  289.                 any string arguments as dbus.String objects (a subclass of
  290.                 unicode).
  291.             `byte_arrays` : bool
  292.                 If True, the handler function will receive any byte-array
  293.                 arguments as dbus.ByteArray objects (a subclass of str).
  294.                 If False (default) it will receive any byte-array
  295.                 arguments as a dbus.Array of dbus.Byte (subclasses of:
  296.                 a list of ints).
  297.             `sender_keyword` : str
  298.                 If not None (the default), the handler function will receive
  299.                 the unique name of the sending endpoint as a keyword
  300.                 argument with this name.
  301.             `destination_keyword` : str
  302.                 If not None (the default), the handler function will receive
  303.                 the bus name of the destination (or None if the signal is a
  304.                 broadcast, as is usual) as a keyword argument with this name.
  305.             `interface_keyword` : str
  306.                 If not None (the default), the handler function will receive
  307.                 the signal interface as a keyword argument with this name.
  308.             `member_keyword` : str
  309.                 If not None (the default), the handler function will receive
  310.                 the signal name as a keyword argument with this name.
  311.             `path_keyword` : str
  312.                 If not None (the default), the handler function will receive
  313.                 the object-path of the sending object as a keyword argument
  314.                 with this name.
  315.             `message_keyword` : str
  316.                 If not None (the default), the handler function will receive
  317.                 the `dbus.lowlevel.SignalMessage` as a keyword argument with
  318.                 this name.
  319.             `arg...` : unicode or UTF-8 str
  320.                 If there are additional keyword parameters of the form
  321.                 ``arg``\\ *n*, match only signals where the *n*\\ th argument
  322.                 is the value given for that keyword parameter. As of this
  323.                 time only string arguments can be matched (in particular,
  324.                 object paths and signatures can't).
  325.             `named_service` : str
  326.                 A deprecated alias for `bus_name`.
  327.         """
  328.         self._require_main_loop()
  329.         named_service = keywords.pop('named_service', None)
  330.         if named_service is not None:
  331.             if bus_name is not None:
  332.                 raise TypeError('bus_name and named_service cannot both be specified')
  333.             bus_name is not None
  334.             bus_name = named_service
  335.             warn = warn
  336.             import warnings
  337.             warn('Passing the named_service parameter to add_signal_receiver by name is deprecated: please use positional parameters', DeprecationWarning, stacklevel = 2)
  338.         
  339.         match = SignalMatch(self, bus_name, path, dbus_interface, signal_name, handler_function, **keywords)
  340.         self._signals_lock.acquire()
  341.         
  342.         try:
  343.             by_interface = self._signal_recipients_by_object_path.setdefault(path, { })
  344.             by_member = by_interface.setdefault(dbus_interface, { })
  345.             matches = by_member.setdefault(signal_name, [])
  346.             matches.append(match)
  347.         finally:
  348.             self._signals_lock.release()
  349.  
  350.         return match
  351.  
  352.     
  353.     def _iter_easy_matches(self, path, dbus_interface, member):
  354.         if path is not None:
  355.             path_keys = (None, path)
  356.         else:
  357.             path_keys = (None,)
  358.         if dbus_interface is not None:
  359.             interface_keys = (None, dbus_interface)
  360.         else:
  361.             interface_keys = (None,)
  362.         if member is not None:
  363.             member_keys = (None, member)
  364.         else:
  365.             member_keys = (None,)
  366.         for path in path_keys:
  367.             by_interface = self._signal_recipients_by_object_path.get(path, None)
  368.             if by_interface is None:
  369.                 continue
  370.             
  371.             for dbus_interface in interface_keys:
  372.                 by_member = by_interface.get(dbus_interface, None)
  373.                 if by_member is None:
  374.                     continue
  375.                 
  376.                 for member in member_keys:
  377.                     matches = by_member.get(member, None)
  378.                     if matches is None:
  379.                         continue
  380.                     
  381.                     for m in matches:
  382.                         yield m
  383.                     
  384.                 
  385.             
  386.         
  387.  
  388.     
  389.     def remove_signal_receiver(self, handler_or_match, signal_name = None, dbus_interface = None, bus_name = None, path = None, **keywords):
  390.         named_service = keywords.pop('named_service', None)
  391.         if named_service is not None:
  392.             if bus_name is not None:
  393.                 raise TypeError('bus_name and named_service cannot both be specified')
  394.             bus_name is not None
  395.             bus_name = named_service
  396.             warn = warn
  397.             import warnings
  398.             warn('Passing the named_service parameter to remove_signal_receiver by name is deprecated: please use positional parameters', DeprecationWarning, stacklevel = 2)
  399.         
  400.         new = []
  401.         deletions = []
  402.         self._signals_lock.acquire()
  403.         
  404.         try:
  405.             by_interface = self._signal_recipients_by_object_path.get(path, None)
  406.             if by_interface is None:
  407.                 return None
  408.             by_member = by_interface.get(dbus_interface, None)
  409.             if by_member is None:
  410.                 return None
  411.             matches = by_member.get(signal_name, None)
  412.             if matches is None:
  413.                 return None
  414.             for match in matches:
  415.                 if handler_or_match is match or match.matches_removal_spec(bus_name, path, dbus_interface, signal_name, handler_or_match, **keywords):
  416.                     deletions.append(match)
  417.                     continue
  418.                 matches is None
  419.                 new.append(match)
  420.             
  421.             by_member[signal_name] = new
  422.         finally:
  423.             self._signals_lock.release()
  424.  
  425.         for match in deletions:
  426.             self._clean_up_signal_match(match)
  427.         
  428.  
  429.     
  430.     def _clean_up_signal_match(self, match):
  431.         pass
  432.  
  433.     
  434.     def _signal_func(self, message):
  435.         '''D-Bus filter function. Handle signals by dispatching to Python
  436.         callbacks kept in the match-rule tree.
  437.         '''
  438.         if not isinstance(message, SignalMessage):
  439.             return HANDLER_RESULT_NOT_YET_HANDLED
  440.         dbus_interface = message.get_interface()
  441.         path = message.get_path()
  442.         signal_name = message.get_member()
  443.         for match in self._iter_easy_matches(path, dbus_interface, signal_name):
  444.             match.maybe_handle_message(message)
  445.         
  446.         return HANDLER_RESULT_NOT_YET_HANDLED
  447.  
  448.     
  449.     def call_async(self, bus_name, object_path, dbus_interface, method, signature, args, reply_handler, error_handler, timeout = -1, utf8_strings = False, byte_arrays = False, require_main_loop = True):
  450.         '''Call the given method, asynchronously.
  451.  
  452.         If the reply_handler is None, successful replies will be ignored.
  453.         If the error_handler is None, failures will be ignored. If both
  454.         are None, the implementation may request that no reply is sent.
  455.  
  456.         :Returns: The dbus.lowlevel.PendingCall.
  457.         :Since: 0.81.0
  458.         '''
  459.         if object_path == LOCAL_PATH:
  460.             raise DBusException('Methods may not be called on the reserved path %s' % LOCAL_PATH)
  461.         object_path == LOCAL_PATH
  462.         if dbus_interface == LOCAL_IFACE:
  463.             raise DBusException('Methods may not be called on the reserved interface %s' % LOCAL_IFACE)
  464.         dbus_interface == LOCAL_IFACE
  465.         get_args_opts = {
  466.             'utf8_strings': utf8_strings,
  467.             'byte_arrays': byte_arrays }
  468.         message = MethodCallMessage(destination = bus_name, path = object_path, interface = dbus_interface, method = method)
  469.         
  470.         try:
  471.             message.append(signature = signature, *args)
  472.         except Exception:
  473.             e = None
  474.             logging.basicConfig()
  475.             _logger.error('Unable to set arguments %r according to signature %r: %s: %s', args, signature, e.__class__, e)
  476.             raise 
  477.  
  478.         if reply_handler is None and error_handler is None:
  479.             self.send_message(message)
  480.             return None
  481.         if reply_handler is None:
  482.             reply_handler = _noop
  483.         
  484.         if error_handler is None:
  485.             error_handler = _noop
  486.         
  487.         
  488.         def msg_reply_handler(message):
  489.             if isinstance(message, MethodReturnMessage):
  490.                 reply_handler(*message.get_args_list(**get_args_opts))
  491.             elif isinstance(message, ErrorMessage):
  492.                 error_handler(DBusException(name = message.get_error_name(), *message.get_args_list()))
  493.             else:
  494.                 error_handler(TypeError('Unexpected type for reply message: %r' % message))
  495.  
  496.         return self.send_message_with_reply(message, msg_reply_handler, timeout, require_main_loop = require_main_loop)
  497.  
  498.     
  499.     def call_blocking(self, bus_name, object_path, dbus_interface, method, signature, args, timeout = -1, utf8_strings = False, byte_arrays = False):
  500.         '''Call the given method, synchronously.
  501.         :Since: 0.81.0
  502.         '''
  503.         if object_path == LOCAL_PATH:
  504.             raise DBusException('Methods may not be called on the reserved path %s' % LOCAL_PATH)
  505.         object_path == LOCAL_PATH
  506.         if dbus_interface == LOCAL_IFACE:
  507.             raise DBusException('Methods may not be called on the reserved interface %s' % LOCAL_IFACE)
  508.         dbus_interface == LOCAL_IFACE
  509.         get_args_opts = {
  510.             'utf8_strings': utf8_strings,
  511.             'byte_arrays': byte_arrays }
  512.         message = MethodCallMessage(destination = bus_name, path = object_path, interface = dbus_interface, method = method)
  513.         
  514.         try:
  515.             message.append(signature = signature, *args)
  516.         except Exception:
  517.             e = None
  518.             logging.basicConfig()
  519.             _logger.error('Unable to set arguments %r according to signature %r: %s: %s', args, signature, e.__class__, e)
  520.             raise 
  521.  
  522.         reply_message = self.send_message_with_reply_and_block(message, timeout)
  523.         args_list = reply_message.get_args_list(**get_args_opts)
  524.         if len(args_list) == 0:
  525.             return None
  526.         if len(args_list) == 1:
  527.             return args_list[0]
  528.         return tuple(args_list)
  529.  
  530.     
  531.     def call_on_disconnection(self, callable):
  532.         '''Arrange for `callable` to be called with one argument (this
  533.         Connection object) when the Connection becomes
  534.         disconnected.
  535.  
  536.         :Since: 0.83.0
  537.         '''
  538.         self._Connection__call_on_disconnection.append(callable)
  539.  
  540.  
  541.